// 二叉树前序遍历
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
function TreeNode(val, left, right) {
  this.val = (val===undefined ? 0 : val)
  this.left = (left===undefined ? null : left)
  this.right = (right===undefined ? null : right)
}
var preorderTraversal = function (root) {
  const stack = [];
  let res = [];//用来存放前序遍历进入的元素
  while (root || stack.length) {
      while (root) {
          stack.push(root);
          res.push(root.val)
          root = root.left;
      }
      root = stack.pop();
      root = root.right;
  }
  return res;
};

// 二叉树中序遍历
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
  const stack = [];
  let res = [];
  while(root || stack.length) {
      while(root) {
          stack.push(root);
          root = root.left;
      }
      root = stack.pop();
      res.push(root.val)
      root = root.right;
  }
  return res
};

// 二叉树后序遍历
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function(root) {
  const stack = [];
  const res = [];
  while(root || stack.length) {
      while(root) {
          stack.push(root);
          res.unshift(root.val)
          root = root.right;
      }
      root = stack.pop();
      root = root.left;
  }
  return res
};